package com.itbaizhan.ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itbaizhan.ruiji.common.CustomException;
import com.itbaizhan.ruiji.dto.SetmealDto;
import com.itbaizhan.ruiji.mapper.SetmealMapper;
import com.itbaizhan.ruiji.pojo.Setmeal;
import com.itbaizhan.ruiji.pojo.SetmealDish;
import com.itbaizhan.ruiji.service.SetmealDishService;
import com.itbaizhan.ruiji.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     *
     */

    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void addMealwithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        Long setmealDtoId = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDtoId);
            return setmealDish;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

    }

    @Override
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        long count = this.count(queryWrapper);
        if (count>0){
            throw new CustomException("有商品正在发售中。。。");
        }
        this.removeByIds(ids);
        LambdaQueryWrapper<SetmealDish> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId,ids);
        queryWrapper1.orderByAsc(SetmealDish::getUpdateTime);
        setmealDishService.remove(queryWrapper1);

    }

}
